package com.uziot.bucket.transactional.service;

import com.uziot.bucket.transactional.dao.domain.SysUser;
import com.uziot.bucket.transactional.dao.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @author shidt
 * @version V1.0
 * @className SysUserService
 * @date 2022-02-18 22:15:14
 * @description
 */

@Service
public class SysUserTransService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;


    public int add(SysUser sysUser) {
        return addUser(sysUser);
    }

    /**
     * 测试手动开启事务并设置事务级别的方式
     *
     * @param sysUser 用户
     * @return 影响的条数
     */
    int addUser(SysUser sysUser) {
        // 独立的事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus tranStatus = transactionManager.getTransaction(def);
        int i = 0;
        try {
            // 必须在操作完成后提交事务
            SysUser user = sysUserMapper.selectUserByUserName(sysUser.getUserName());
            if (null != user) {
                throw new RuntimeException("用户已存在！");
            }
            i = sysUserMapper.insert(sysUser);
            transactionManager.commit(tranStatus);
        } catch (Exception e) {
            transactionManager.rollback(tranStatus);
        }
        return i;
    }


}
